import { defineEventHandler, getQuery, readBody } from 'h3'
import { query, execute } from '../utils/db'
import { customAlphabet } from 'nanoid'
import type { RowDataPacket } from 'mysql2'
import { ResponseCode, sendSuccessResponse, sendErrorResponse } from '~/server/utils/response'

const alphabet = process.env.alphabet || '123456789abcdefghijklmnopqrstuvwxyz'
const nanoid = customAlphabet(alphabet, 10)

interface User extends RowDataPacket {
  user_id: string
  username: string
  password?: string
  disable?: number
  role?: string
  role_id?: number
  create_time?: string
}

export default defineEventHandler(async (event) => {
  try {
    const method = event.node.req.method

    // 获取用户列表 (GET /api/users)
    if (method === 'GET') {
      const queryParams = getQuery(event)
      const page = Number(queryParams.page) || 1
      const size = Number(queryParams.size) || 10

      // 参数验证（使用标准化错误响应）
      if (page < 1 || size < 1) {
        return sendErrorResponse(event, ResponseCode.BAD_REQUEST, '分页参数无效')
      }

      const sql = `
       SELECT 
        u.user_id, 
        u.username, 
        u.create_time, 
        u.disable, 
        r.role_id, 
        r.role,
        u.id  -- 假设你想查询用户的id
      FROM user u 
      LEFT JOIN role r ON u.role_id = r.role_id  -- 正确的JOIN条件
      ORDER BY u.create_time DESC 
      LIMIT ?, ?
      `
      const { results: users } = await query<User[]>(sql, [
        (page - 1) * size,
        size
      ])

      // 获取总数
      const countSql = 'SELECT COUNT(*) as total FROM user'
      const { results: [{ total }] } = await query<RowDataPacket[]>(countSql)

      return sendSuccessResponse(event, {
        list: users,
        pagination: {
          total,
          currentPage: page,
          perPage: size,
          totalPages: Math.ceil(total / size)
        }
      }, '用户列表获取成功')
    }

    // 创建用户 (POST /api/users)
    if (method === 'POST') {
      const body = await readBody(event)
      const { username, password, role_id = 2 } = body

      // 参数验证
      if (!username || !password) {
        return sendErrorResponse(event, ResponseCode.BAD_REQUEST, '用户名和密码不能为空')
      }

      // 检查用户名是否已存在
      const checkSql = 'SELECT user_id FROM user WHERE username = ? LIMIT 1'
      const { results: [existingUser] } = await query<User[]>(checkSql, [username])

      if (existingUser) {
        return sendErrorResponse(event, ResponseCode.CONFLICT, '用户名已存在')
      }

      // 创建用户
      const userId = nanoid()
      const createSql = `
        INSERT INTO user 
        (user_id, username, password, role_id) 
        VALUES (?, ?, ?, ?)
      `
      await execute(createSql, [userId, username, password, role_id])

      // 返回新创建的用户
      const { results: [newUser] } = await query<User[]>(
        'SELECT user_id, username, role_id FROM user WHERE user_id = ? LIMIT 1',
        [userId]
      )

      return sendSuccessResponse(event, newUser, '用户创建成功')
    }

    // 更新用户 (PUT /api/users/:id)
    if (method === 'PUT') {

      console.log('请求头:', getHeaders(event))
      console.log('原始请求体:', await readRawBody(event))

      const body = await readBody(event)
      console.log('解析后的请求体:', body)

      const { user_id, username, password, role_id } = body

      // 参数验证
      if (!user_id) {
        return sendErrorResponse(event, ResponseCode.BAD_REQUEST, '用户ID不能为空')
      }

      // 构建更新字段
      const updateFields = []
      const params = []

      if (username) {
        updateFields.push('username = ?')
        params.push(username)
      }

      if (password) {
        updateFields.push('password = ?')
        params.push(password)
      }

      if (role_id) {
        updateFields.push('role_id = ?')
        params.push(role_id)
      }

      if (updateFields.length === 0) {
        return sendErrorResponse(event, ResponseCode.BAD_REQUEST, '没有需要更新的字段')
      }

      // 执行更新
      const updateSql = `UPDATE user SET ${updateFields.join(', ')} WHERE user_id = ?`
      params.push(user_id)
      await execute(updateSql, params)

      // 返回更新后的用户
      const { results: [updatedUser] } = await query<User[]>(
        'SELECT user_id, username, role_id FROM user WHERE user_id = ? LIMIT 1',
        [user_id]
      )

      return sendSuccessResponse(event, updatedUser, '用户更新成功')
    }

    // 删除用户 (DELETE /api/users/:id)
    if (method === 'DELETE') {
      const { id } = getQuery(event)

      if (!id) {
        return sendErrorResponse(event, ResponseCode.BAD_REQUEST, '用户ID不能为空')
      }

      // 检查用户是否存在
      const { results: [user] } = await query<User[]>(
        'SELECT user_id FROM user WHERE user_id = ? LIMIT 1',
        [id]
      )

      if (!user) {
        return sendErrorResponse(event, ResponseCode.NOT_FOUND, '用户不存在')
      }

      // 执行删除
      await execute(
        'DELETE FROM user WHERE user_id = ? LIMIT 1',
        [id]
      )

      return sendSuccessResponse(event, null, '用户删除成功')
    }

    // 切换用户状态 (PATCH /api/users/:id/disable)
    if (method === 'PATCH' && event.path?.endsWith('/disable')) {
      const { id } = getQuery(event)
      const body = await readBody(event)
      const { disable } = body

      if (!id || disable === undefined) {
        return sendErrorResponse(event, ResponseCode.BAD_REQUEST, '用户ID和状态不能为空')
      }

      await execute(
        'UPDATE user SET disable = ? WHERE user_id = ? LIMIT 1',
        [disable ? 1 : 0, id]
      )

      return sendSuccessResponse(event, null, `用户已${disable ? '禁用' : '启用'}`)
    }

    // 未匹配的路由
    return sendErrorResponse(event, ResponseCode.NOT_FOUND, '接口不存在')
  } catch (error) {
    // 统一错误处理
    console.error('用户接口错误:', error)
    return sendErrorResponse(event, ResponseCode.INTERNAL_ERROR, '服务器内部错误')
  }
})